home *** CD-ROM | disk | FTP | other *** search
/ SPACE 1 / SPACE - Library 1 - Volume 1.iso / misc~1 / 199 / src / grep.c < prev    next >
Encoding:
C/C++ Source or Header  |  1988-03-14  |  1.1 KB  |  68 lines

  1. /* look for strings in a file */
  2.  
  3. #include "stdio.h"
  4.  
  5. #define MAXLINE    256
  6.  
  7. char     line[MAXLINE];
  8. char    str[MAXLINE];
  9.  
  10. main(argc, argv) char *argv[]; {
  11.     int i;
  12.     char *nm;
  13.     FILE *f;
  14.     if (argc == 1) {
  15.         fprintf(stderr, "usage: grep pat file ...\n");
  16.         exit(1);
  17.     }
  18.  
  19.     strcpy(str, argv[1]);
  20.     lower(str);
  21.     nm = NULL;
  22.  
  23.     if (argc == 2) {
  24.         grep(nm, str, stdin);
  25.     }
  26.     else for (i = 2; i < argc; i++) {
  27.         if ((f = fopen(argv[i], "r")) != NULL) {
  28.             if (argc > 3) nm = argv[i];
  29.             grep(nm, str, f);
  30.             fclose(f);
  31.         }
  32.         else     fprintf(stderr, "can't open %s\n", argv[i]);
  33.     }
  34. }
  35.  
  36. lower(s) char *s; { /* don't need this if cmd works right */
  37.     char c;
  38.     while (c = *s) {
  39.         if (c >= 'A' && c <= 'Z')
  40.             *s = c - 'A' +  'a';
  41.         s++;
  42.     }
  43. }
  44.  
  45. grep(name, str, f) char *name, *str; FILE *f; {
  46.     while (fgets(line, MAXLINE, f)) {
  47.         lower(line);
  48.         if (in(str, line)) {
  49.             if (name) printf("%s: ", name);
  50.             printf("%s", line);
  51.         }
  52.     }
  53. }
  54.  
  55. in(s, l) char *s, *l; {
  56.     char c, i;
  57.     i = 0;
  58.     while (c = *l++) {
  59.         if (c == s[i]) {
  60.             i++;
  61.             if (s[i] == 0) return 1;
  62.         }
  63.         else    i = 0;
  64.     }
  65.     return 0;
  66. }
  67.  
  68.